<template>
  <div class="sign-form-item">
    <div class="title"><div class="dot"/>签约信息</div>
    <el-form
      ref="formRef"
      :model="modelData"
      :rules="formRules"
      :label-width="labelWidth"
      class="lineHeight32"
      label-position="right">
      <el-row type="flex" class="response-el-row">
        <el-col :span="rowSpan">
          <el-form-item label="签单签约经纪" prop="agentId">
            <selectWithUserLoad
              v-model="agentObj"
              :hide-select-list="modelData.agentId?[{id:modelData.agentId, userName: modelData.agentName}] : []"
              :style="{ 'width': showMobilePage ? 'auto' : '240px' }"
              placeholder="请选择人员"
              key-name="id"
              value-type="object"
              label-name="userName"
              filterable
              clearable
            />
          </el-form-item>
        </el-col>
        <el-form-item label="签约所属部门" prop="signDeptId">
          <el-cascader
            v-model="modelData.signDeptId"
            :show-all-levels="false"
            :options="deptTreeList"
            :props="{
              emitPath:false,
              value: 'id',
              label: 'name',
              checkStrictly: true,
              multiple: false,
            }"
            class="width240"
            placeholder="请选择"
            size="small"
            collapse-tags
            filterable
            clearable>
            <template slot-scope="{ data }">
              <el-tooltip v-if="data.name.length > 14" placement="top-start" effect="dark">
                <div slot="content" style="max-width: 150px;">{{ data.name }}</div>
                <span class="inline-tag ellipsisOne">{{ data.name }}</span>
              </el-tooltip>
              <span v-else>{{ data.name || '--' }}</span>
            </template>
          </el-cascader>
        </el-form-item>
        <el-col :span="rowSpan">
          <el-form-item prop="cooperation" label="合作方式">
            <selectWithoutHttp v-model="modelData.cooperation" :list-data="cooperationOption" key-name="value" label-name="label" class="width240" @change="changeCooperation"/>
            <!-- <selectWithoutHttp v-model="modelData.cooperation" :list-data="cooperationOption" key-name="value" label-name="label" class="width240"/> -->
          </el-form-item>
        </el-col>
        <el-col :span="rowSpan">
          <el-form-item label="协作部门" prop="cooperationDepartment">
            <filterCascader
              ref="filterCascader"
              v-model="modelData.cooperationDepartment"
              :options="deptTreeList"
              :key="cascaderKey"
              class="width240"
              popper-class="tag-overflow"
              placeholder="请选择协作部门"
            />
          </el-form-item>
        </el-col>
        <el-col :span="rowSpan">
          <el-form-item label="签约有效期" prop="signDate">
            <el-date-picker
              v-model="modelData.signDate"
              :disabled="unChangeSignDate"
              type="daterange"
              align="right"
              size="small"
              class="width240"
              value-format="timestamp"
              unlink-panels
              range-separator="-"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              format="yyyy/MM/dd" />
          </el-form-item>
        </el-col>
        <el-col :span="rowSpan">
          <el-form-item label="自动续约" prop="autoRenewal">
            <selectWithoutHttp v-model="modelData.autoRenewal" :list-data="autoRenewalOptions" class="width240" key-name="id" label-name="label"/>
          </el-form-item>
        </el-col>
        <el-col :span="rowSpan">
          <el-form-item prop="schedule" label="目前进度">
            <selectWithoutHttp v-model="modelData.schedule" :list-data="scheduleOption" key-name="value" label-name="label" class="width240"/>
          </el-form-item>
        </el-col>
        <el-col :span="rowSpan">
          <el-form-item label="工作微信" prop="workWxCode">
            <el-input v-model="modelData.workWxCode" :maxlength="100" class="width240" placeholder="请输入工作微信" type="text" size="small" />
          </el-form-item>
        </el-col>
        <el-col :span="rowSpan">
          <el-form-item label="推荐理由" prop="reason">
            <el-input v-model="modelData.reason" :maxlength="1000" resize="none" class="width240" placeholder="请描述推荐该账号的理由" type="textarea" size="small" />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
  </div>
</template>

<script>
import selectWithUserLoad from '@/components/Common/selectWithUserLoad';
import selectWithoutHttp from '@/components/Common/selectWithoutHttp';
import upAttachment from '@/components/Common/upAttachment/index';
import filterCascader from '@/components/Common/filterCascader';
import { hasRouteAuth } from '@/utils/permission';
import { cooperationOption, scheduleOption } from '@/utils/accountCommonData';
import { getDepartmentAll } from '@/api/config';
import ElMessage from '@/utils/message';

export default {
  components: { selectWithUserLoad, selectWithoutHttp, upAttachment, filterCascader },
  model: {
    prop: 'modelData',
    event: 'changeValue'
  },
  props: {
    modelData: {
      type: Object,
      default: () => {
        return {};
      }
    },
    labelWidth: {
      type: String,
      default: '110px'
    },
    rowSpan: {
      type: Number,
      default: 12
    },
    showMobilePage: {
      type: Boolean,
      default: false
    },
    accountItem: {
      type: Object,
      default: null
    }
  },
  data() {
    return {
      cooperationOption,
      scheduleOption,
      unChangeSignDate: false,
      autoRenewalOptions: [{ id: 0, label: '否' }, { id: 1, label: '是' }],
      formRules: {
        agentId: [{ required: true, trigger: 'change', message: '请选择签单签约经纪' }],
        signDeptId: [{ required: true, trigger: 'change', message: '请选择签约所属部门' }],
        cooperationDepartment: [{ required: true, trigger: 'change', message: '请选择协作部门' }],
        supplier: [{ required: true, trigger: 'change', message: '请输入供应商名称' }],
        signDate: [{ required: true, trigger: 'change', message: '请选择签约有效期' }],
        cooperation: [{ required: true, trigger: 'change', message: '请选择合作方式' }],
        schedule: [{ required: true, trigger: 'change', message: '请选择目前进度' }]
      },
      deptTreeList: [],
      mediaCenter: {},
      newMedia: {},
      cascaderKey: 1000
    };
  },
  computed: {
    agentObj: {
      get() {
        return {
          id: this.modelData.agentId,
          userName: this.modelData.agentName
        };
      },
      set(data) {
        this.modelData.agentName = data.userName;
        this.modelData.agentId = data.id;
      }
    }
  },
  created() {
    this.queryDeptTreeList();
    if (this.$route && this.$route.params && this.$route.params.id && this.modelData.legalCode && this.modelData.legalCode.id) {
      this.unChangeSignDate = true;
    }
  },
  methods: {
    hasRouteAuth,
    validateForm(validate = true) {
      return new Promise((resolve, reject) => {
        if (validate) {
          this.$refs.formRef.validate(valid => {
            if (valid) {
              resolve(valid);
            } else {
              reject();
            }
          });
        } else {
          resolve(true);
        }
      });
    },
    /* // 获取部门列表
    queryDeptTreeList() {
      getDepartmentAll().then(res => {
        this.deptTreeList = (res && res.data) || [];
        if (this.accountItem.initNew) {
        // 默认执行经纪组
          const findId = this.setCooperationDepartment(this.deptTreeList);
          findId && this.modelData.cooperationDepartment.push(findId);
        }
      }).catch(e => {
        console.log(e);
      });
    }, */
    // 获取部门列表
    queryDeptTreeList() {
      getDepartmentAll().then(res => {
        this.deptTreeList = (res && res.data) || [];
        if (this.accountItem.initNew) {
        // 默认执行经纪组
          const findId = this.setCooperationDepartment(this.deptTreeList);
          findId && this.modelData.cooperationDepartment.push(findId);
        }
        // 保存媒介中心、新媒体商业平台id
        this.foreachDeptName(this.deptTreeList, '媒介中心');
        this.foreachDeptName(this.deptTreeList, '新媒体商业平台');
      }).catch(e => {
        console.log(e);
      });
    },
    foreachDeptName(data, name) {
      for (let i = 0; i < data.length; i++) {
        if (data[i].name === name) {
          if (name === '媒介中心') {
            this.mediaCenter = data[i];
          } else if (name === '新媒体商业平台') {
            this.newMedia = data[i];
          }
          break;
        } else if (data[i].children && data[i].children.length) {
          this.foreachDeptName(data[i].children, name);
        }
      }
    },
    setCooperationDepartment(list) {
      const findName = '执行经纪组';
      for (let i = 0; i < list.length; i++) {
        if (list[i].name === findName) {
          return list[i].id;
        } else if (list[i].children) {
          const result = this.setCooperationDepartment(list[i].children);
          if (result) {
            return result;
          }
        }
      }
      return null;
    },
    // 上传文件
    complateSetData({ data, fileName }, key) {
      const fileList = {
        name: fileName,
        url: data.url,
        time: new Date().getTime()
      };
      if (typeof data === 'string') {
        fileList.url = data;
      } else {
        fileList.url = data.url;
      }
      if (this.modelData[key]) {
        this.modelData[key].push(fileList);
      } else {
        this.modelData[key] = [fileList];
      }
    },
    removeFileList({ file, index }, key) {
      this.modelData[key].splice(index, 1);
    },
    numberInputChange(key) {
      if (this.modelData[key]) this.modelData[key] = Number(this.modelData[key]).toFixed(2);
    },
    changeCooperation(val) {
      if (val !== 2) {
        // 移除媒介中心
        const index = this.modelData.cooperationDepartment.indexOf(this.mediaCenter.id);
        if (index !== -1) {
          this.cascaderKey++;
          this.modelData.cooperationDepartment.splice(index, 1);
          this.$refs.filterCascader.onChange(this.modelData.cooperationDepartment, {});
        }
      }
      if (val !== 1) {
        // 移除新媒体商业平台
        const index = this.modelData.cooperationDepartment.indexOf(this.newMedia.id);
        if (index !== -1) {
          this.cascaderKey++;
          this.modelData.cooperationDepartment.splice(index, 1);
          this.$refs.filterCascader.onChange(this.modelData.cooperationDepartment, {});
        }
      }
      if (val === 2) {
        // 回填执行经纪组
        const findId = this.setCooperationDepartment(this.deptTreeList);
        if (!findId) {
          ElMessage.warning('无法找到对应部门【执行经纪组】，请联系研发部进行自动回填的修改或手动选择部门');
        } else {
          this.cascaderKey++;
          this.modelData.cooperationDepartment.push(findId);
        }
      }
      if (val === 1 && this.newMedia) {
        // 选中新媒体商业平台
        if (!this.mediaCenter.id) {
          ElMessage.warning('无法找到对应部门【新媒体商业平台】，请联系研发部进行自动回填的修改或手动选择部门');
        } else {
          this.cascaderKey++;
          this.modelData.cooperationDepartment.push(this.newMedia.id);
          this.newMedia.hasChildren = true;
          this.newMedia.check = true;
          this.$refs.filterCascader.onChange(this.modelData.cooperationDepartment, this.newMedia);
        }
      }
    }
  }
};
</script>

<style lang="scss" scoped>
.width240 {
  width: 240px;
  &::v-deep {
    .el-select {
      width: 240px;
    }
    .el-input__inner {
      width: 240px;
    }
  }
}
.title {
  font-size: 16px;
  font-weight: 600;
  text-align: left;
  color: #333333;
  line-height: 16px;
  margin-bottom: 16px;
  display: flex;
  align-items: center;
  .dot {
    width: 4px;
    height: 4px;
    background-color: #406EFF;
    margin-right: 6px;
  }
}
.mock-input {
  &::v-deep {
    .el-input-number__increase,.el-input-number__decrease {
      display: none;
    }
    .el-input__inner {
      text-align: left;
      padding-left: 8px;
    }
  }
}
</style>
